package com.bill99.rpc.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import com.bill99.rpc.common.Constants;
import com.bill99.rpc.registry.url.ServiceUrl;

/**
 * @author sheng.zhang
 * 
 */
public class UrlUtils {
	
	public static String encode(String value) {
		if (value == null || value.length() == 0) {
			return "";
		}
		try {
			return URLEncoder.encode(value, Constants.DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static String decode(String value) {
		if (value == null || value.length() == 0) {
			return "";
		}
		try {
			return URLDecoder.decode(value, Constants.DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public static String buildHessianUrl(ServiceUrl serviceUrl) {
		StringBuilder buf = new StringBuilder();
		buf.append("http://").append(serviceUrl.getHost()).append(":")
				.append(serviceUrl.getPort()).append("/")
				.append(serviceUrl.getPath());
		return buf.toString();
	}

}